package com.tf_cut.admin.api.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tf_cut.admin.api.vo.*;
import com.tf_cut.admin.backend.api.BackEndApi;
import com.tf_cut.admin.common.pojo.ApiResult;
import com.tf_cut.admin.common.pojo.PageInfo;
import com.tf_cut.admin.common.pojo.Result;
import com.tf_cut.admin.person.vo.PersonAndAccountVo;
import com.tf_cut.admin.seller.vo.SellerAndAccountVo;
import com.tf_cut.admin.seller.vo.SellerRefAgentVo;
import com.tf_cut.admin.service.vo.ServiceRefSellerVo;
import com.tf_cut.admin.sys.sysauthority.service.SysAuthorityService;
import com.tf_cut.admin.sys.sysauthority.vo.SysAuthorityVo;
import com.tf_cut.admin.sys.sysuser.pojo.SysUser;
import com.tf_cut.admin.sys.sysuser.service.SysUserService;
import com.tf_cut.admin.sys.sysuser.vo.SysUserVo;
import com.tf_cut.admin.sys.sysuserauthority.service.SysUserAuthorityService;
import com.tf_cut.admin.sys.sysuserauthority.vo.SysUserAuthorityVo;
import com.tf_cut.admin.util.CommUtil;
import com.tf_cut.admin.util.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/api")
@Slf4j
public class ApiController {

	@Autowired
	private BackEndApi backEndApi;

	@Autowired
	private SysUserService sysUserService;

	@Autowired
	private SysAuthorityService sysAuthorityService;

	@Autowired
	private SysUserAuthorityService sysUserAuthorityService;

	@Value("${mobile.upload.path}")
	private String filePath;

	private String uploadPath = "mobile/upload/";

	@PostMapping("/singlePaid")
	public ApiResult<SinglePaidRes> singlePaid(@Validated @RequestBody SinglePaid singlePaid,
			HttpServletRequest request) {
		SinglePaidRes res = new SinglePaidRes();
		String sellerInfo = backEndApi.getSellerInfo(singlePaid.getAppKey());
		ApiResult<SinglePaidRes> result;

		SellerAndAccountVo sellerVo = JSON.parseObject(sellerInfo, SellerAndAccountVo.class);

		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}

		String[] split = sellerVo.getAdoptIp().split(",");
		boolean contains = Arrays.asList(split).contains(ip);
		if (contains == false) {
			return ApiResult.of(null, 1103, "IP校验失败");
		}

		if (!MD5Util.verify(singlePaid.toSignStr() + sellerVo.getAppSecret(), singlePaid.getSign().toUpperCase())) {
			return ApiResult.of(null, 1102, "加密错误");
		}

		if (singlePaid.getAppIdKey() != null && !singlePaid.getAppIdKey().equals("")) {
			sellerInfo = backEndApi.getSellerInfo(singlePaid.getAppIdKey());
			sellerVo = JSON.parseObject(sellerInfo, SellerAndAccountVo.class);
		}

		if (StringUtils.isBlank(sellerInfo)) {
			return ApiResult.of(null, 1101, "无可用商户");
		}

		PersonAndAccountVo PersonAndAccountVo = backEndApi.findbyqueryPerson(singlePaid.getIdentityCardNum());
		if (PersonAndAccountVo == null) {
			return ApiResult.of(null, 1108, "无此用户");
		}

		String balance = backEndApi.getBalance(sellerVo.getSellerId());
		if (Double.parseDouble(balance) - Double.parseDouble(singlePaid.getAmount()) < 0) {
			return ApiResult.of(null, 1104, "余额不足");
		}

		SysUser sysUserVo = sysUserService.queryAppKey(sellerVo.getLoginId());

		singlePaid.setSellerId(sellerVo.getSellerId());

		String paidRes = backEndApi.singlePaid(JSON.toJSONString(singlePaid), sysUserVo.getPlatform(),
				sysUserVo.getMerchantNumber());
		HashMap<String, String> paidResMap = JSON.parseObject(paidRes, HashMap.class);
		if ("0".equalsIgnoreCase(paidResMap.get("code"))) {
			res.setOrderId(paidResMap.get("data"));
			result = ApiResult.of(res, 0, "调用成功");
		} else {
			result = ApiResult.of(res, Integer.parseInt(paidResMap.get("code")), paidResMap.get("msg"));
		}

		return result;
	}

	@PostMapping("/userSign")
	public ApiResult<Map<String, String>> userSign(@Validated @RequestBody UserSign userSign,
			HttpServletRequest request) {
		String sellerInfo = backEndApi.getSellerInfo(userSign.getAppKey());
		SellerAndAccountVo sellerVo = JSON.parseObject(sellerInfo, SellerAndAccountVo.class);

		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}

		String[] split = sellerVo.getAdoptIp().split(",");
		boolean contains = Arrays.asList(split).contains(ip);
		if (contains == false) {
			return ApiResult.of(null, 1103, "IP校验失败");
		}

		if (!MD5Util.verify(userSign.toSignStr() + sellerVo.getAppSecret(), userSign.getSign().toUpperCase())) {
			return ApiResult.of(null, 1102, "加密错误");
		}

		if (StringUtils.isAnyBlank(userSign.getIdCardBackPic(), userSign.getIdCardFrontPic(), userSign.getSignPic(),
				userSign.getAuthPic())) {
			return ApiResult.of(null, 1100, "参数缺失");
		}

		if (StringUtils.isBlank(sellerInfo)) {
			return ApiResult.of(null, 1101, "无可用商户");
		}

		// 判断手机号重复
		Integer byLoginName = sysUserService.queryByLoginName(userSign.getMobile());
		if (byLoginName >= 1) {
			return ApiResult.of(null, 1107, "该用户已签约");
		}

		String FileFullPath = filePath + uploadPath;
		String idFontFullPath = CommUtil.BASE64CodeToBeImage(
				userSign.getIdCardFrontPic().substring(userSign.getIdCardFrontPic().indexOf(",") + 1), FileFullPath,
				"jpg");

		String idBackFullPath = CommUtil.BASE64CodeToBeImage(
				userSign.getIdCardBackPic().substring(userSign.getIdCardBackPic().indexOf(",") + 1), FileFullPath,
				"jpg");
		String signFullPath = CommUtil.BASE64CodeToBeImage(
				userSign.getSignPic().substring(userSign.getSignPic().indexOf(",") + 1), FileFullPath, "jpg");
		String authFullPath = CommUtil.BASE64CodeToBeImage(
				userSign.getAuthPic().substring(userSign.getAuthPic().indexOf(",") + 1), FileFullPath, "jpg");

		// 判断手机号重复
		SysUser byMobile = sysUserService.queryByMobile(userSign.getMobile());
		Result<SysUserVo> save = null;
		if (byMobile == null) {
			// 新增系统用户
			SysUserVo sysUserVo = SysUserVo.builder().createTime(new Date()).updateTime(new Date())
					.lastChangePwdTime(new Date()).loginName(userSign.getMobile()).userName(userSign.getIdCardName())
					.password(MD5Util.md5("xyd123456")).valid("Y").limitMultiLogin("Y").build();
			save = this.sysUserService.save(sysUserVo);
			// 增加用户权限
			List<SysAuthorityVo> seller_user = this.sysAuthorityService
					.list(SysAuthorityVo.builder().authorityName("PERSON_USER").build()).getData();
			if (seller_user == null || seller_user.isEmpty()) {
				return ApiResult.of(null, 9999, "系统异常");
			}

			SysUserAuthorityVo build = SysUserAuthorityVo.builder().userId(save.getData().getUserId())
					.authorityId(seller_user.get(0).getAuthorityId()).createTime(new Date()).build();
			this.sysUserAuthorityService.save(build);
		}

		// 增加个人信息
		JSONObject object = new JSONObject();
		if (byMobile == null) {
			object.put("loginId", save.getData().getUserId());
		} else {
			object.put("loginId", byMobile.getUserId());
			object.put("personId", sysUserService.findByPersonId(userSign.getMobile()));
		}
		object.put("loginName", userSign.getMobile());
		object.put("personName", userSign.getIdCardName());
		object.put("cardType", 1);
		object.put("cardCode", userSign.getIdCardNum());
		object.put("mobile", userSign.getMobile());
		object.put("cardImgOne", uploadPath + idFontFullPath);
		object.put("cardImgTwo", uploadPath + idBackFullPath);
		object.put("signImg", uploadPath + signFullPath);
		object.put("authImg", uploadPath + authFullPath);
		object.put("remark", "");// 清空驳回原因
		object.put("cardStatus", "X");// 没有认证
		String result = this.backEndApi.insertPersonAndAccount(object.toJSONString());
		JSONObject jsonObject = JSONObject.parseObject(result, JSONObject.class);
		backEndApi.sendMail("1", userSign.getIdCardName(), userSign.getMobile(), userSign.getIdCardNum());

		if (!jsonObject.getBoolean("flag")) {
			return ApiResult.of(null, 9999, "系统异常");
		} else {
			Map<String, String> resMap = new HashMap<>();
			JSONObject jsonObjects = (JSONObject) jsonObject.get("data");
			resMap.put("personId", jsonObjects.get("personId").toString());
			System.out.println("成功" + resMap);
			return ApiResult.of(resMap, 0, "成功");
		}
	}

	@PostMapping("/userSignQuery")
	public ApiResult<Map<String, String>> userSignQuery(@Validated @RequestBody UserSign userSign,
			HttpServletRequest request) {

		String sellerInfo = backEndApi.getSellerInfo(userSign.getAppKey());
		SellerAndAccountVo sellerVo = JSON.parseObject(sellerInfo, SellerAndAccountVo.class);

		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}

		String[] split = sellerVo.getAdoptIp().split(",");
		boolean contains = Arrays.asList(split).contains(ip);
		if (contains == false) {
			return ApiResult.of(null, 1103, "IP校验失败");
		}

		if (StringUtils.isBlank(sellerInfo)) {
			return ApiResult.of(null, 1101, "无可用商户");
		}
		if (!MD5Util.verify(userSign.toSignStr() + sellerVo.getAppSecret(), userSign.getSign().toUpperCase())) {
			return ApiResult.of(null, 1102, "加密错误");
		}

		PersonAndAccountVo personAndAccountVo = new PersonAndAccountVo();
		personAndAccountVo.setCardCode(userSign.getIdCardNum());
		// personAndAccountVo.setCardStatus("Y");
		String json = JSON.toJSONString(personAndAccountVo);
		json = backEndApi.queryPersonInfoList(json);
		PageInfo returnPageInfo = JSONObject.parseObject(json, PageInfo.class);
		if (returnPageInfo.getRows().isEmpty()) {
			return ApiResult.of(null, 1108, "无此用户");
		}
		List<PersonAndAccountVo> rVos = JSONArray.parseArray(returnPageInfo.getRows().toString(),
				PersonAndAccountVo.class);
		PersonAndAccountVo rVo = rVos.get(0);
		String r = "0";
		if ("Y".equalsIgnoreCase(rVo.getCardStatus())) {
			r = "2";
		} else if ("N".equalsIgnoreCase(rVo.getCardStatus())) {
			r = "3";
		} else {
			r = "1";
		}
		Map<String, String> rMap = new HashMap<>();
		rMap.put("idCardNum", rVo.getCardCode());
		rMap.put("signStatus", r);
		rMap.put("remark", rVo.getRemark());
		return ApiResult.of(rMap, 0, "成功");
	}

	@PostMapping("/balanceQuery")
	public ApiResult<Map<String, String>> balanceQuery(@Validated @RequestBody BaseParam baseParam,
			HttpServletRequest request) {
		String sellerInfo = backEndApi.getSellerInfo(baseParam.getAppKey());
		SellerAndAccountVo sellerVo = JSON.parseObject(sellerInfo, SellerAndAccountVo.class);

		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		String[] split = sellerVo.getAdoptIp().split(",");
		boolean contains = Arrays.asList(split).contains(ip);
		if (contains == false) {
			return ApiResult.of(null, 1103, "IP校验失败");
		}

		if (StringUtils.isBlank(sellerInfo)) {
			return ApiResult.of(null, 1101, "无可用商户");
		}
		if (!MD5Util.verify(baseParam.toSignStr() + sellerVo.getAppSecret(), baseParam.getSign().toUpperCase())) {
			return ApiResult.of(null, 1102, "加密错误");
		}

		String balance = backEndApi.getBalance(sellerVo.getSellerId());
		Map<String, String> resMap = new HashMap<>();
		resMap.put("balanceAmount", balance);
		return ApiResult.of(resMap, 0, "成功");
	}

	@PostMapping("/balanceOsQuery")
	public ApiResult<Map<String, String>> balanceOsQuery(@Validated @RequestBody BaseOsParam baseParam,
			HttpServletRequest request) {
		String sellerInfo = backEndApi.getSellerInfo(baseParam.getAppKey());
		SellerAndAccountVo sellerVo = JSON.parseObject(sellerInfo, SellerAndAccountVo.class);

		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		String[] split = sellerVo.getAdoptIp().split(",");
		boolean contains = Arrays.asList(split).contains(ip);
		if (contains == false) {
			return ApiResult.of(null, 1103, "IP校验失败");
		}

		if (StringUtils.isBlank(sellerInfo)) {
			return ApiResult.of(null, 1101, "无可用商户");
		}
		if (!MD5Util.verify(baseParam.toSignStr() + sellerVo.getAppSecret(), baseParam.getSign().toUpperCase())) {
			return ApiResult.of(null, 1102, "加密错误");
		}

		String sellerInfoVo = backEndApi.getSellerInfo(baseParam.getAppIdKey());
		SellerAndAccountVo selleAccountVo = JSON.parseObject(sellerInfoVo, SellerAndAccountVo.class);

		String balance = backEndApi.getBalance(selleAccountVo.getSellerId());
		Map<String, String> resMap = new HashMap<>();
		resMap.put("balanceAmount", balance);
		return ApiResult.of(resMap, 0, "成功");
	}

	@PostMapping("/paidResultQuery")
	public ApiResult<List<Map>> paidResultQuery(@Validated @RequestBody SinglePaidQry singlePaidQry,
			HttpServletRequest request) {
		String sellerInfo = backEndApi.getSellerInfo(singlePaidQry.getAppKey());
		SellerAndAccountVo sellerVo = JSON.parseObject(sellerInfo, SellerAndAccountVo.class);
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}

		String[] split = sellerVo.getAdoptIp().split(",");
		boolean contains = Arrays.asList(split).contains(ip);
		if (contains == false) {
			return ApiResult.of(null, 1103, "IP校验失败");
		}

		if (StringUtils.isBlank(sellerInfo)) {
			return ApiResult.of(null, 1101, "无可用商户");
		}
		if (!MD5Util.verify(singlePaidQry.toSignStr() + sellerVo.getAppSecret(),
				singlePaidQry.getSign().toUpperCase())) {
			return ApiResult.of(null, 1102, "加密错误");
		}

		String[] ords = singlePaidQry.getCustomerNo().split(",");
		List<String> noList = Arrays.asList(ords);

		String r = backEndApi.qryRecord(JSON.toJSONString(noList));
		List<Map> rmap = JSONArray.parseArray(r, Map.class);
		return ApiResult.of(rmap, 0, "成功");
	}

	@PostMapping("/sellerInsert")
	public ApiResult<Map<String, String>> sellerInsert(@Validated @RequestBody SellerPaidInfo sellerPaidInfo,
			HttpServletRequest request) throws Exception {

		String sellerInfo = backEndApi.getSellerInfo(sellerPaidInfo.getAppKey());
		SellerAndAccountVo sellerVo = JSON.parseObject(sellerInfo, SellerAndAccountVo.class);
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}

		if (StringUtils.isBlank(sellerInfo)) {
			return ApiResult.of(null, 1101, "无可用商户");
		}
		
		String[] split = sellerVo.getAdoptIp().split(",");
		boolean contains = Arrays.asList(split).contains(ip);
		if (contains == false) {
			return ApiResult.of(null, 1103, "IP校验失败");
		}

		if (!MD5Util.verify(sellerPaidInfo.toSignStr() + sellerVo.getAppSecret(),
				sellerPaidInfo.getSign().toUpperCase())) {
			return ApiResult.of(null, 1102, "加密错误");
		}

		SellerRefAgentVo sellerRefAgentVo = new SellerRefAgentVo();
		Result<SysUserVo> save = null;

		if (sellerPaidInfo.getAppIdKey() == null || sellerPaidInfo.getAppIdKey().equals("")) {
			// 判断手机号重复
			Integer byLoginName = sysUserService.queryByLoginName(sellerPaidInfo.getSellerMobile());
			if (byLoginName >= 1) {
				return ApiResult.of(null, 1107, "该用户已签约");
			}

			// 判断商户名称重复
			Integer queryBySellerName = backEndApi.queryBySellerName(sellerPaidInfo.getSellerName(),
					sellerPaidInfo.getSellerCompanyName());
			if (queryBySellerName >= 1) {
				return ApiResult.of(null, 1109, "商户名重复");
			}

			// 判断代理商是否存在
			sellerRefAgentVo = backEndApi.queryBySellerRefAgent(sellerPaidInfo.getAgentNumber());
			if (sellerRefAgentVo == null) {
				return ApiResult.of(null, 1110, "未查询到代理商");
			}

		} else {
			// 判断商户名称重复
			Integer queryBySellerName = backEndApi.queryBySellerName(sellerPaidInfo.getSellerName(),
					sellerPaidInfo.getSellerCompanyName());
			if (queryBySellerName > 1) {
				return ApiResult.of(null, 1109, "商户名重复");
			}
		}

		String FileFullPath = filePath + uploadPath;

		String idFontFullPath = CommUtil.BASE64CodeToBeImage(sellerPaidInfo.getBusinessLicenseFile()
				.substring(sellerPaidInfo.getBusinessLicenseFile().indexOf(",") + 1), FileFullPath, "jpg");

		String conFile = CommUtil.decryptByBase64(
				sellerPaidInfo.getContractFile().substring(sellerPaidInfo.getContractFile().indexOf(",") + 1),
				FileFullPath, "docx");

		String serviceType = backEndApi.findByType(sellerPaidInfo.getServiceType());
		if (serviceType == null) {
			return ApiResult.of(null, 1111, "未查询到服务类型");
		}

		if (sellerPaidInfo.getAppIdKey() == null || sellerPaidInfo.getAppIdKey().equals("")) {
			int findByLoginName = sysUserService.findByMobile(sellerPaidInfo.getSellerMobile());
			if (findByLoginName < 1) {
				// 新增系统用户
				SysUserVo sysUserVo = SysUserVo.builder().createTime(new Date()).updateTime(new Date())
						.lastChangePwdTime(new Date()).loginName(sellerPaidInfo.getSellerMobile())
						.userName(sellerPaidInfo.getSellerName()).password(MD5Util.md5("xyd123456")).valid("Y")
						.limitMultiLogin("Y").build();
				save = this.sysUserService.save(sysUserVo);
				// 增加用户权限
				List<SysAuthorityVo> seller_user = this.sysAuthorityService
						.list(SysAuthorityVo.builder().authorityName("SELLER_USER").build()).getData();
				// 如果获取商户权限菜单失败
				if (seller_user == null || seller_user.isEmpty()) {
					return ApiResult.of(null, 9999, "系统错误");
				}
			}
		}

		// 增加商户信息
		JSONObject object = new JSONObject();
		if (sellerPaidInfo.getAppIdKey() == null || sellerPaidInfo.getAppIdKey().equals("")) {
			if(save != null){
				object.put("loginId", save.getData().getUserId());				
			}
			object.put("loginName", sellerPaidInfo.getSellerMobile());
		}
		if (sellerPaidInfo.getAppIdKey() != null && !sellerPaidInfo.getAppIdKey().equals("")) {
			SellerAndAccountVo sellerAndAccountVo = backEndApi.queryBySellerId(sellerPaidInfo.getAppIdKey());
			if (sellerAndAccountVo == null) {
				return ApiResult.of(null, 1101, "未查询到签约商户");
			}
			object.put("sellerId", sellerAndAccountVo.getSellerId());
		}
		object.put("sellerName", sellerPaidInfo.getSellerName());
		object.put("sellerCompanyName", sellerPaidInfo.getSellerCompanyName());
		object.put("sellerMobile", sellerPaidInfo.getSellerMobile());
		object.put("sellerCity", sellerPaidInfo.getSellerCity());
		object.put("loadDate", sellerPaidInfo.getLoadDate());
		object.put("maxPay", sellerPaidInfo.getMaxPay());
		object.put("minPay", sellerPaidInfo.getMinPay());
		object.put("taxPayerCode", sellerPaidInfo.getTaxPayerCode());
		object.put("businessLicenseFile", idFontFullPath);
		object.put("contractFile", conFile);
		object.put("sellerAddress", sellerPaidInfo.getSellerAddress());
		object.put("sellerPhone", sellerPaidInfo.getSellerPhone());
		object.put("sellerBank", sellerPaidInfo.getSellerBank());
		object.put("sellerBankAccount", sellerPaidInfo.getSellerBankAccount());
		object.put("isOld", "N");
		object.put("serviceType", serviceType);
		object.put("sellerState", "Y");// 默认不冻结
		object.put("isAuthentication", "X");// 没有认证
		String result = this.backEndApi.insertSellerAndAccount(object.toJSONString());
		JSONObject jsonObject = JSONObject.parseObject(result, JSONObject.class);
		SellerAndAccountVo avo = JSON.parseObject(jsonObject.get("data").toString(), SellerAndAccountVo.class);
		if (sellerPaidInfo.getAppIdKey() == null || sellerPaidInfo.getAppIdKey().equals("")) {
			// 关联服务商
			ServiceRefSellerVo serviceRefSellerVo = new ServiceRefSellerVo();
			serviceRefSellerVo.setSellerId(avo.getSellerId());
			serviceRefSellerVo.setRefState("Y");
			serviceRefSellerVo.setServiceId("bd8e4d36aab34743abbaa9f56c67bfb5");
			String json = backEndApi.saveSellerRefService(JSON.toJSONString(serviceRefSellerVo));

			// 关联代理商
			sellerRefAgentVo.setSellerId(avo.getSellerId());
			sellerRefAgentVo.setServerAmountPoint(new BigDecimal(sellerPaidInfo.getSignPoint()));
			sellerRefAgentVo.setRefState("Y");
			sellerRefAgentVo.setServiceFormula(1);
			String jsons = backEndApi.saveSellerRefAgent(JSON.toJSONString(sellerRefAgentVo));
		}

		Map<String, String> resMap = new HashMap<>();
		if (avo.getAppKey() != null) {
			resMap.put("appKey", avo.getAppKey());
			resMap.put("appSecret", avo.getAppSecret());
		}
		resMap.put("sellerName", avo.getSellerName());
		resMap.put("sellerCompanyName", avo.getSellerCompanyName());
		resMap.put("sellerMobile", avo.getSellerMobile());
		resMap.put("serviceType", serviceType);
		resMap.put("sellerPhone", avo.getSellerPhone());
		System.out.println("成功" + resMap);
		return ApiResult.of(resMap, 0, "成功");
	}

	@PostMapping("/findBySeller")
	public ApiResult<Map<String, String>> findBySeller(@Validated @RequestBody SellerQuery sellerQuery,
			HttpServletRequest request) throws Exception {

		String sellerInfo = backEndApi.getSellerInfo(sellerQuery.getAppKey());
		SellerAndAccountVo sellerVo = JSON.parseObject(sellerInfo, SellerAndAccountVo.class);
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}

		String[] split = sellerVo.getAdoptIp().split(",");
		boolean contains = Arrays.asList(split).contains(ip);
		if (contains == false) {
			return ApiResult.of(null, 1103, "IP校验失败");
		}

		if (StringUtils.isBlank(sellerInfo)) {
			return ApiResult.of(null, 1101, "无可用商户");
		}
		if (!MD5Util.verify(sellerQuery.toSignStr() + sellerVo.getAppSecret(), sellerQuery.getSign().toUpperCase())) {
			return ApiResult.of(null, 1102, "加密错误");
		}

		SellerAndAccountVo avo = backEndApi.queryBySellerId(sellerQuery.getAppIdKey());
		if (avo == null) {
			return ApiResult.of(null, 1101, "无可用商户");
		}

		Map<String, String> resMap = new HashMap<>();
		resMap.put("sellerName", avo.getSellerName());
		resMap.put("sellerCompanyName", avo.getSellerCompanyName());
		resMap.put("sellerMobile", avo.getSellerMobile());
		resMap.put("serviceType", avo.getServiceType());
		resMap.put("sellerPhone", avo.getSellerPhone());
		resMap.put("sellerCity", avo.getSellerCity());
		resMap.put("loadDate", avo.getLoadDate());
		resMap.put("maxPay", avo.getMaxPay().toString());
		resMap.put("minPay", avo.getMinPay().toString());
		resMap.put("taxPayerCode", avo.getTaxPayerCode());
		resMap.put("sellerAddress", avo.getSellerAddress());
		resMap.put("sellerBank", avo.getSellerBank());
		resMap.put("serviceType", avo.getServiceType());
		resMap.put("appKey", avo.getAppKey());
		resMap.put("appSecret", avo.getAppSecret());
		resMap.put("status", avo.getIsAuthentication());
		resMap.put("serverBankName", "中国建设银行股份有限公司乐安支行");
		resMap.put("serverName", "江西佰和信息科技有限公司");
		resMap.put("serverBankNumber", "36050185075000001021");
		System.out.println("成功" + resMap);
		return ApiResult.of(resMap, 0, "成功");
	}

}
